class WebSocketService {
  constructor() {
    this.ws = null
    this.messageHandlers = new Set()
    this.statusHandlers = new Set()
    // 由于你的域名是 https，WebSocket 应该使用 wss
    this.wsUrl = 'wss://www.ywen.site/wss'
  }

  connect(flag) {
    try {
      this.ws = new WebSocket(this.wsUrl)
      
      this.ws.onopen = () => {
        console.log('WebSocket 连接已建立;readyState:',this.ws.readyState);
        const token = localStorage.getItem('token')
        // 确保连接已经完全建立
        if (this.ws.readyState === WebSocket.OPEN) {
          // 在这里发送消息
          if (token) {
            this.ws.send(JSON.stringify({ 
              type: 'auth', 
              token 
            }))
          }
          if (flag === 'login') {
            this.ws.send(JSON.stringify({ 
              type: 'login', 
              token 
            }))
          }
        }
        
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          console.log('收到消息:', data)
          if (data.type === 'message') {
            this.messageHandlers.forEach(handler => handler(data))
          } else if (data.type === 'userStatus') {
            console.log('用户状态更新:', data.users)
            // 确保 users 数组存在
            if (Array.isArray(data.users)) {
              this.statusHandlers.forEach(handler => handler(data.users))
            }
          }
        } catch (error) {
          console.error('WebSocket 消息处理错误:', error)
        }
      }

      this.ws.onclose = (event) => {
        console.log('WebSocket 连接已关闭:', event)
        // 断线重连
        setTimeout(() => {
          console.log('尝试重新连接...')
          this.connect()
        }, 3000)
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
      }

    } catch (error) {
      console.error('WebSocket 连接错误:', error)
      // 连接失败后重试
      setTimeout(() => this.connect(), 3000)
    }
  }

  sendMessage(messageData) {
    console.log(this.ws.readyState,'---',WebSocket.OPEN);
    if (this.ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'message',
        content: messageData.content,
        contentType: messageData.type,
        to: messageData.to, // 添加接收者
        timestamp: new Date().getTime()
      }
      this.ws.send(JSON.stringify(message))
    } else {
      console.warn('WebSocket 未连接，消息发送失败')
    }
  }

  onMessage(handler) {
    this.messageHandlers.add(handler)
    return () => this.messageHandlers.delete(handler)
  }

  onUserStatus(handler) {
    this.statusHandlers.add(handler)
    return () => this.statusHandlers.delete(handler)
  }

  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }
}

export const wsService = new WebSocketService()